//
//  WBComPoseViewController.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/21.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComPoseViewController: UIViewController {

    /// 文本编辑视图
    @IBOutlet weak var textView: WBComposeTextView!
    
    /// 底部工具栏
    @IBOutlet weak var toolbar: UIToolbar!
    
    /// 发布按钮
    @IBOutlet var sendBtn: UIButton!
    
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    /// 标题标签 换行热键 option+回车
    //逐行选中文版并且设置属性。如果想要调整行间距，可以增加一个空行，设置空行的字体，lineHeight
    @IBOutlet var titleLabel: UILabel!
    /// 表情输入视图
    lazy var emoticonView: TYCEmoticonInputView = TYCEmoticonInputView.inputView {[weak self] (emoticon) in
        self?.textView.insertEmoticon(em: emoticon)
    }
    
    
    /// 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setUpUI()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    //MARK:监听键盘的方法
    @objc func keyboardChanged(n: NSNotification) {
        
        //1.目标rect
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else {
            return
        }
        //2.设置底部约束的高度
        let offset = view.bounds.height - rect.origin.y
        //3.更新底部约束
        toolbarBottomCons.constant = offset
        //4.动画更新的约束
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //MARK: - 按钮监听方法
    /// 发布微博
    @IBAction func postStatus() {
        print("发布微博")
        //1.获取微博文字
        let text = textView.emoticonText
        //FIXME:发布临时带图片的微博
        let image: UIImage? = nil
        
        WBNetworkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in
            print(result)
            //修改指示器样式样式
            SVProgressHUD.setDefaultStyle(.dark)
            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.showInfo(withStatus: message)
            //如果成功，延迟一段时间关闭当前窗口
            if isSuccess {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                    //恢复样式
                    SVProgressHUD.setDefaultStyle(.light)
                    self.close()
                })
            }
        }
    }
    @objc private func emoticonKeyboard() {
        //textView.inputView 就是文本框的输入视图
        //如果使用系统默认的键盘，输入视图为nil
        // 1> 测试键盘视图
//        let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 271))
//        keyboardView.backgroundColor = UIColor.blue
        // 2> 设置键盘视图
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        // 3> 刷新键盘视图
        textView.reloadInputViews()
    }
}

// MARK: - UITextViewDelegate
/**
 通知： 一对多，只要有注册的监听者，在注销监听之前，都可以接收到通知
 代理： 一对一，最后设置的代理对象有效
 
 苹果日常开发中，代理的监听方式是最多的！
 - 代理是发生事件时，直接让代理执行协议方法
    代理的效率更高
    直接打反向传值
 - 通知是发生事件时，将通知发送给通知中心，通知中心再’广播‘通知
    通知相对要低一些
    如果层次嵌套的非常深，可以使用通知传值
 */
extension WBComPoseViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        sendBtn.isEnabled = textView.hasText
    }
}

extension WBComPoseViewController {
    
    func setUpUI() {
        view.backgroundColor = UIColor.white
        setUpNavgationItem()
        setUpToolItem()
    }
    
    func setUpToolItem() {
        let itemSettings = [
            ["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        
        for s in itemSettings {
            guard let imageName = s["imageName"] else {
                continue
            }
            
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            let btn = UIButton()
            btn.setImage(image, for: .normal)
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            //判断actionName
            if let actionName = s["actionName"]{
                //给按钮添加监听方法
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            //追加按钮
            items.append(UIBarButtonItem(customView: btn))
            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    func setUpNavgationItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        navigationItem.titleView = titleLabel
        sendBtn.isEnabled = false
    }
}
